package com.hfzy.ihk.web.aliyuncall.biz;

import com.hfzy.ihk.common.util.ValidateUtils;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.facade.aliyuncall.enums.MainCallTypeEnum;
import com.hfzy.ihk.facade.aliyuncall.vo.CallHistory;
import com.hfzy.ihk.web.aliyuncall.constant.Constants;
import com.hfzy.ihk.web.aliyuncall.constant.RedisKey;
import com.hfzy.ihk.web.aliyuncall.support.SampleMemoryCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/4/29.
 * @author wws
 * 点击拨号业务逻辑
 */
@Component("clickCallBiz")
@Lazy
public class ClickCallBiz {

    @Autowired
    private  AliyunCallOutBiz aliyunCallOutBiz;


    @Autowired
    private AliyunAsrCallOutBiz aliyunAsrCallOutBiz;

    private static final Logger logger = LoggerFactory.getLogger(ClickCallBiz.class);


    /**
     * 双呼呼出
     * @return 正常情况下：返回null
     * */
    public Map<String,String> handleClickCallWebSocket( String mainCallPhone,String targetCallPhone ,String machineFrom ,
                                                          String createUserId ,String dataId  ,String whereFrom ,String pageFrom ,
                                                          String mainCallType ,String commitTo , String city, String customerName,
                                                        String showNum ,String project,String propertyNo,String objectId,String sessionId,String callTaskId,String packageId) {
        Map<String, String> validateMap;
        CallHistory callHistory = new CallHistory();

        if(StringUtil.isNotNull(commitTo)){ //不为空就使用该线路 这个一般前端控制
            callHistory.setCommitTo(Integer.valueOf(commitTo));
        }else{
            callHistory.setCommitTo(10);
        }
        try {

            validateMap = validateClickCallWebSocket(mainCallPhone, targetCallPhone, machineFrom,
                    String.valueOf(createUserId), String.valueOf(dataId), String.valueOf(whereFrom),
                    String.valueOf(pageFrom), String.valueOf(mainCallType), String.valueOf(callHistory.getCommitTo()), customerName,sessionId,callTaskId,packageId);


            if (validateMap !=null && Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION.equals(validateMap.get(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE))) {
                return validateMap;
            }


            //获取主显号码
            //爱家可能会将主显号传过来
            if(StringTools.isEmpty(showNum)) {
                if (Constants.NULL_STR.equals(showNum) || StringTools.isEmpty(showNum))
                    showNum = inTurnUseShowNum(city != null ? Integer.valueOf(city) : Constants.NEGATIVE, createUserId,
                            mainCallPhone, targetCallPhone, Integer.valueOf(whereFrom), false, callHistory.getCommitTo());

                if (StringTools.isNotempty(showNum)) {
                    callHistory.setShowNum(showNum);
                } else {
                    validateMap = new HashMap<>(6);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_1);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
                    validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

                    return validateMap;
                }
            }else{
                callHistory.setShowNum(showNum);
            }

            if(StringUtil.isEmpty(dataId))
                callHistory.setDataId("-1");
            else
                callHistory.setDataId(dataId);

            callHistory.setSessionId(sessionId);

            callHistory.setMainCallPhone(mainCallPhone);
            callHistory.setTargetCallPhone(targetCallPhone);
            callHistory.setMachineFrom(machineFrom);
            callHistory.setWhereFrom(Integer.valueOf(whereFrom));
            callHistory.setPageFrom(Integer.valueOf(StringTools.notSetValue(pageFrom,"-1")));

            //* 置业默认：mainCallPhone:客户号码。targetCallPhone：经纪号码
            callHistory.setMainCallType(MainCallTypeEnum.MAIN_CALL_PHONE_IS_CUSTOMER.getValue());

            callHistory.setCreateUserId(StringTools.notSetValue(createUserId,"-1"));
            callHistory.setCity(Integer.valueOf(StringTools.notSetValue(city,"-1")));

            callHistory.setCustomerName(StringTools.notSetValue(customerName,"-1"));//客户名称

            callHistory.setCallType(0);//通话类型：呼出(0)、呼入(1)

            //callHistory.setCreateTime(new Date());
            callHistory.setCreateTime(new Date());
            callHistory.setProject(StringTools.notSetValue(project,"-1"));
            callHistory.setPropertyNo(StringTools.notSetValue(propertyNo,"-1"));
            callHistory.setObjectId(StringTools.notSetValue(objectId,"-1"));
            callHistory.setCallTaskId(StringTools.notSetValue(callTaskId,"-1"));
            callHistory.setPackageId(StringTools.notSetValue(packageId,"-1"));


            //数据进入业务类
            aliyunCallOutBiz.todoCallOut(callHistory);


        } catch (Exception e) {

            logger.error("->>>>呼叫异常",e);

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_3);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            logger.error("webSocketListener exception:", e);
        } finally {
            mainCallPhone = null;
            targetCallPhone = null;
            machineFrom = null;
            createUserId = null;
            dataId = null;
            whereFrom = null;
            pageFrom = null;
            mainCallType = null;
            //          commitTo = null;
            customerName = null;
        }

        return validateMap;
    }



    public String inTurnUseShowNum(Integer city,String createUserId,String mainCallPhone, String targetCallPhone,
                                   Integer whereFrom, boolean isCallOutUserCallIn, Integer commitTo){

        return "057128204523";

    }


    /**
     * 验证从websocket呼出 双呼
     * @return 正常情况下：返回null
     * */
    public Map<String,String> validateClickCallWebSocket( String mainCallPhone,String targetCallPhone ,String machineFrom ,
                                                String createUserId ,String dataId  ,String whereFrom ,String pageFrom ,
                                                String mainCallType ,String commitTo ,String customerName,String sessionId,String callTaskId,String packageId ) {
        if("11".equals(whereFrom)||"25".equals(whereFrom)) //用于保利测试的不判断,用于crm freeswitch测试的不判断
            return null;

        Map<String, String> validateMap = null;

        if (SampleMemoryCache.isBadCustomerPhone(mainCallPhone) || SampleMemoryCache.isBadCustomerPhone(targetCallPhone)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_12);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        if( mainCallPhone == null || //主叫；由拨号时发送过来
            targetCallPhone == null || //被叫；由拨号时发送过来
            machineFrom == null ||//机器码：用于定位websocket对象（websocket）
            createUserId == null ||
            whereFrom == null || //来源：app(0),置业(1)
            pageFrom == null || //app盘源(0),app联动call(1),置业盘源(2)，置业联动call(3)? （websocket）
            callTaskId == null || customerName == null||packageId==null){

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_4);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
            return validateMap;
        }

//        if (!ValidateUtils.isNumeric(mainCallPhone) ||
                if(!ValidateUtils.isNumeric(targetCallPhone)) { //freeswitch 可能主叫不是数字，是账号来的

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_2_2);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        if (!ValidateUtils.isNumeric(whereFrom) ||
                !ValidateUtils.isNumeric(mainCallType)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_2);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        if (mainCallPhone.equals(targetCallPhone) && !pageFrom.equals("5")) { //拦截主叫被叫相同的；测试座机页面允许
            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_5);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }
        return validateMap;
    }


    /**
     * 验证从websocket呼出 智能外呼验证
     * @return 正常情况下：返回null
     * */
    public Map<String,String> validateAsrClickCallWebSocket( String mainCallPhone ,String machineFrom ,
                                                          String createUserId ,String dataId  ,String whereFrom ,String pageFrom
                                                          ,String commitTo ,String customerName,String sessionId,String callTaskId,String packageId ) {

        Map<String, String> validateMap = null;

        if (SampleMemoryCache.isBadCustomerPhone(mainCallPhone)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_12);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        if( mainCallPhone == null || //主叫；由拨号时发送过来
                machineFrom == null ||//机器码：用于定位websocket对象（websocket）
                createUserId == null ||
                whereFrom == null || //来源：app(0),置业(1)
            //    pageFrom == null || //app盘源(0),app联动call(1),置业盘源(2)，置业联动call(3)? （websocket）
                callTaskId == null || customerName == null||packageId==null){

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_4);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
            return validateMap;
        }

        if (!ValidateUtils.isNumeric(createUserId) ||
                !ValidateUtils.isNumeric(whereFrom) ||
                !ValidateUtils.isNumeric(pageFrom)) {

            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_2);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);

            return validateMap;
        }

        return validateMap;
    }



    /**
     * Asr只能外呼呼出
     * @return 正常情况下：返回null
     * */
    public Map<String,String> handleAsrClickCallWebSocket( String mainCallPhone,String machineFrom ,
                                                        String createUserId ,String dataId  ,String whereFrom ,String pageFrom ,
                                                        String commitTo , String city, String customerName,
                                                        String showNum ,String project,String propertyNo,String objectId,String sessionId,String callTaskId,String packageId,String actionCodeBreak,String voiceCode,String voiceText,String company) {
        Map<String, String> validateMap;
        CallHistory callHistory = new CallHistory();
        callHistory.setCommitTo(12); //智能外呼用12
        try {

            validateMap = validateAsrClickCallWebSocket(mainCallPhone, machineFrom,
                    String.valueOf(createUserId), String.valueOf(dataId), String.valueOf(whereFrom),
                    String.valueOf(pageFrom), String.valueOf(callHistory.getCommitTo()), customerName,sessionId,callTaskId,packageId);

            if (validateMap !=null && Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION.equals(validateMap.get(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE))) {
                return validateMap;
            }

            //获取主显号码
            if(Constants.NULL_STR.equals(showNum) || StringTools.isEmpty(showNum) )
                showNum ="057128204523"; //这里从redis 获取

            if (StringTools.isNotempty(showNum)) {
                callHistory.setShowNum(showNum);
            } else {
                validateMap = new HashMap<>(6);
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_1);
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
                validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
                return validateMap;
            }

            if(StringUtil.isEmpty(dataId))
                callHistory.setDataId("-1");
            else
                callHistory.setDataId(dataId);

            callHistory.setSessionId(sessionId);

            callHistory.setMainCallPhone(mainCallPhone);
            callHistory.setMachineFrom(machineFrom);
            callHistory.setWhereFrom(Integer.valueOf(whereFrom));
            callHistory.setPageFrom(Integer.valueOf(StringTools.notSetValue(pageFrom,"-1")));

            //* 置业默认：mainCallPhone:客户号码。targetCallPhone：经纪号码
            callHistory.setMainCallType(MainCallTypeEnum.MAIN_CALL_PHONE_IS_CUSTOMER.getValue());

            callHistory.setCreateUserId(StringTools.notSetValue(createUserId,"-1"));
            callHistory.setCity(Integer.valueOf(StringTools.notSetValue(city,"-1")));

            callHistory.setCustomerName(StringTools.notSetValue(customerName,"-1"));//客户名称

            callHistory.setCallType(0);//通话类型：呼出(0)、呼入(1)

            callHistory.setCreateTime(new Date());

            callHistory.setProject(StringTools.notSetValue(project,"-1"));
            callHistory.setPropertyNo(StringTools.notSetValue(propertyNo,"-1"));
            callHistory.setObjectId(StringTools.notSetValue(objectId,"-1"));
            callHistory.setCallTaskId(StringTools.notSetValue(callTaskId,"-1"));
            callHistory.setPackageId(StringTools.notSetValue(packageId,"-1"));
            if(actionCodeBreak!=null&&actionCodeBreak.equals("1")){
                callHistory.setActionCodeBreak(true);
            }else{
                callHistory.setActionCodeBreak(false);
            }
            callHistory.setVoiceCode(StringTools.notSetValue(voiceCode,"-1"));
            callHistory.setVoiceText(StringTools.notSetValue(voiceText,"-1"));
            //数据进入业务类
            aliyunAsrCallOutBiz.todoCallOut(callHistory);

        } catch (Exception e) {
            e.printStackTrace();
            validateMap = new HashMap<>(6);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_3);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_DATA_ID, dataId);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_PAGE_FROM, pageFrom);
            validateMap.put(Constants.WEB_SOCKET_JSON_KEY_MACHINE_FROM, machineFrom);
            logger.error("webSocketListener exception:", e);
        } finally {
            mainCallPhone = null;
            machineFrom = null;
            createUserId = null;
            dataId = null;
            whereFrom = null;
            pageFrom = null;
            //          commitTo = null;
            customerName = null;
        }

        return validateMap;
    }




}
